// 跨模块数据同步中间件
// 实现模块间的数据共享和状态同步

import { StateCreator } from 'zustand';
import React from 'react';
import { useGlobalStore } from '../globalStore';

// 跨模块事件类型
export type CrossModuleEvent = 
  | { type: 'TAB_OPENED'; payload: { tabId: string; filePath: string } }
  | { type: 'TAB_CLOSED'; payload: { tabId: string; filePath: string } }
  | { type: 'TAB_SAVED'; payload: { tabId: string; filePath: string } }
  | { type: 'VIEW_CHANGED'; payload: { from: string; to: string } }
  | { type: 'WORKSPACE_CHANGED'; payload: { workspace: string } }
  | { type: 'SETTINGS_CHANGED'; payload: { key: string; value: any } }
  | { type: 'ERROR_OCCURRED'; payload: { error: string; module: string } }
  | { type: 'PERFORMANCE_UPDATE'; payload: { metrics: any } };

// 事件监听器类型
export type EventListener = (event: CrossModuleEvent) => void;

// 跨模块同步管理器
class CrossModuleSyncManager {
  private listeners: Map<string, EventListener[]> = new Map();
  private eventHistory: CrossModuleEvent[] = [];
  private maxHistorySize = 100;

  // 注册事件监听器
  subscribe(eventType: CrossModuleEvent['type'], listener: EventListener): () => void {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, []);
    }
    
    this.listeners.get(eventType)!.push(listener);
    
    // 返回取消订阅函数
    return () => {
      const listeners = this.listeners.get(eventType);
      if (listeners) {
        const index = listeners.indexOf(listener);
        if (index > -1) {
          listeners.splice(index, 1);
        }
      }
    };
  }

  // 发布事件
  emit(event: CrossModuleEvent): void {
    // 添加到历史记录
    this.eventHistory.push(event);
    if (this.eventHistory.length > this.maxHistorySize) {
      this.eventHistory.shift();
    }

    // 通知监听器
    const listeners = this.listeners.get(event.type);
    if (listeners) {
      listeners.forEach(listener => {
        try {
          listener(event);
        } catch (error) {
          console.error('Error in cross-module event listener:', error);
        }
      });
    }
  }

  // 获取事件历史
  getEventHistory(): CrossModuleEvent[] {
    return [...this.eventHistory];
  }

  // 清除事件历史
  clearEventHistory(): void {
    this.eventHistory = [];
  }

  // 获取特定类型的事件
  getEventsByType(eventType: CrossModuleEvent['type']): CrossModuleEvent[] {
    return this.eventHistory.filter(event => event.type === eventType);
  }
}

// 全局同步管理器实例
export const crossModuleSync = new CrossModuleSyncManager();

// 跨模块同步中间件
export const withCrossModuleSync = <T>(
  storeCreator: StateCreator<T, [], [], T>,
  moduleName: string
): StateCreator<T, [], [], T> => {
  return (set, get, store) => {
    const originalSet = set;
    
    // 包装set函数以发布状态变化事件
    const wrappedSet = (partial: any, replace?: boolean) => {
      const prevState = get();
      originalSet(partial, replace);
      const newState = get();
      
      // 检测状态变化并发布相应事件
      detectAndEmitStateChanges(prevState, newState, moduleName);
    };

    return storeCreator(wrappedSet, get, store);
  };
};

// 检测状态变化并发布事件
function detectAndEmitStateChanges(prevState: any, newState: any, moduleName: string): void {
  // 根据模块名称检测特定的状态变化
  switch (moduleName) {
    case 'tab':
      detectTabStateChanges(prevState, newState);
      break;
    case 'router':
      detectRouterStateChanges(prevState, newState);
      break;
    case 'global':
      detectGlobalStateChanges(prevState, newState);
      break;
  }
}

// 检测标签页状态变化
function detectTabStateChanges(prevState: any, newState: any): void {
  // 检测新标签页打开
  if (newState.tabs && prevState.tabs) {
    const prevTabIds = new Set(prevState.tabs.keys());
    const newTabIds = new Set(newState.tabs.keys());

    // 新打开的标签页
    for (const tabId of newTabIds) {
      if (!prevTabIds.has(tabId)) {
        const tab = newState.tabs.get(tabId);
        if (tab && typeof tab === 'object' && 'filePath' in tab) {
          crossModuleSync.emit({
            type: 'TAB_OPENED',
            payload: { tabId, filePath: (tab as any).filePath }
          });
        }
      }
    }

    // 关闭的标签页
    for (const tabId of prevTabIds) {
      if (!newTabIds.has(tabId)) {
        const tab = prevState.tabs.get(tabId);
        if (tab && typeof tab === 'object' && 'filePath' in tab) {
          crossModuleSync.emit({
            type: 'TAB_CLOSED',
            payload: { tabId, filePath: (tab as any).filePath }
          });
        }
      }
    }
  }

  // 检测标签页保存
  if (newState.tabs && prevState.tabs) {
    for (const [tabId, newTab] of newState.tabs) {
      const prevTab = prevState.tabs.get(tabId);
      if (prevTab &&
          typeof newTab === 'object' && 'status' in newTab && 'filePath' in newTab &&
          typeof prevTab === 'object' && 'status' in prevTab &&
          (newTab as any).status === 'clean' && (prevTab as any).status !== 'clean') {
        crossModuleSync.emit({
          type: 'TAB_SAVED',
          payload: { tabId, filePath: (newTab as any).filePath }
        });
      }
    }
  }
}

// 检测路由状态变化
function detectRouterStateChanges(prevState: any, newState: any): void {
  if (prevState.currentView !== newState.currentView) {
    crossModuleSync.emit({
      type: 'VIEW_CHANGED',
      payload: { 
        from: prevState.currentView || 'unknown', 
        to: newState.currentView || 'unknown' 
      }
    });
  }
}

// 检测全局状态变化
function detectGlobalStateChanges(prevState: any, newState: any): void {
  // 检测工作区变化
  if (prevState.app?.currentWorkspace !== newState.app?.currentWorkspace) {
    if (newState.app?.currentWorkspace) {
      crossModuleSync.emit({
        type: 'WORKSPACE_CHANGED',
        payload: { workspace: newState.app.currentWorkspace }
      });
    }
  }

  // 检测设置变化
  if (prevState.settings && newState.settings) {
    for (const key in newState.settings) {
      if (prevState.settings[key] !== newState.settings[key]) {
        crossModuleSync.emit({
          type: 'SETTINGS_CHANGED',
          payload: { key, value: newState.settings[key] }
        });
      }
    }
  }

  // 检测错误状态
  if (!prevState.app?.error && newState.app?.error) {
    crossModuleSync.emit({
      type: 'ERROR_OCCURRED',
      payload: { error: newState.app.error, module: 'global' }
    });
  }

  // 检测性能指标更新
  if (prevState.performance?.lastUpdate !== newState.performance?.lastUpdate) {
    crossModuleSync.emit({
      type: 'PERFORMANCE_UPDATE',
      payload: { metrics: newState.performance }
    });
  }
}

// 自动同步hooks
export const useAutoSync = () => {
  const globalStore = useGlobalStore();

  // 设置跨模块同步
  React.useEffect(() => {
    const unsubscribers: (() => void)[] = [];

    // 监听标签页事件，更新全局模块状态
    unsubscribers.push(
      crossModuleSync.subscribe('TAB_OPENED', (event) => {
        globalStore.updateModuleState('editor', {
          tabCount: globalStore.modules.editor.tabCount + 1,
        });
      })
    );

    unsubscribers.push(
      crossModuleSync.subscribe('TAB_CLOSED', (event) => {
        globalStore.updateModuleState('editor', {
          tabCount: Math.max(0, globalStore.modules.editor.tabCount - 1),
        });
      })
    );

    unsubscribers.push(
      crossModuleSync.subscribe('TAB_SAVED', (event) => {
        if (event.type === 'TAB_SAVED') {
          console.log(`Tab saved: ${event.payload.filePath}`);
        }
      })
    );

    // 监听视图变化，更新导航状态
    unsubscribers.push(
      crossModuleSync.subscribe('VIEW_CHANGED', (event) => {
        if (event.type === 'VIEW_CHANGED') {
          console.log(`View changed from ${event.payload.from} to ${event.payload.to}`);
        }
      })
    );

    // 监听工作区变化
    unsubscribers.push(
      crossModuleSync.subscribe('WORKSPACE_CHANGED', (event) => {
        if (event.type === 'WORKSPACE_CHANGED') {
          globalStore.addRecentWorkspace(event.payload.workspace);
        }
      })
    );

    // 监听设置变化
    unsubscribers.push(
      crossModuleSync.subscribe('SETTINGS_CHANGED', (event) => {
        if (event.type === 'SETTINGS_CHANGED') {
          console.log(`Setting ${event.payload.key} changed to:`, event.payload.value);
        }
      })
    );

    // 监听错误事件
    unsubscribers.push(
      crossModuleSync.subscribe('ERROR_OCCURRED', (event) => {
        if (event.type === 'ERROR_OCCURRED') {
          globalStore.addNotification({
            type: 'error',
            title: '错误',
            message: event.payload.error,
            duration: 5000,
          });
        }
      })
    );

    // 清理函数
    return () => {
      unsubscribers.forEach(unsubscribe => unsubscribe());
    };
  }, [globalStore]);
};

// 导出同步管理器和相关工具
export { CrossModuleSyncManager };
